package com.shiro.demo.config;


import com.shiro.demo.dao.PermissionMapper;
import com.shiro.demo.dao.RoleMapper;
import com.shiro.demo.dao.UserMapper;
import com.shiro.demo.entity.AutoToken;
import com.shiro.demo.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        AutoToken token = (AutoToken) principals.getPrimaryPrincipal();
        Set<String> permissions = new HashSet<>(token.getPermissions());
        Set<String> roles = new HashSet<>(token.getRoles());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) auth;
        String username = usernamePasswordToken.getUsername();
        User user = userMapper.getByUserName(username);
        List<String> roles = roleMapper.getRoleByUserId(user.getId());
        List<String> permissions = permissionMapper.getByUserId(user.getId());
        AutoToken autoToken = new AutoToken();
        autoToken.setName(username);
        autoToken.setPermissions(permissions);
        autoToken.setRoles(roles);
        return new SimpleAuthenticationInfo(autoToken, autoToken.getName(), this.getName());
    }
}
